import React, { useState } from 'react';
import { Table, Button, Form, Input, Badge, Modal, Space, Upload } from 'antd';
import { useNavigate } from 'react-router-dom';
import './table.css';
import Model from './modal/Model';
import UploadModalParam from './modal/UploadModelParamPop'

const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{ margin: 0 }}
          rules={[
            {
              required: true,
              message: `Please Input ${title}!`,
            },
          ]}
        >
          <Input />
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

const ModelManage = () => {
  // 静态模型数据
  const staticData = [
    {
      key: 'model_001',
      modelId: 'MODEL_001',
      name: '雷达目标识别AConvNet模型',
      location: '/models/radar/acontnet',
      type: '目标识别',
      attribute: '基于深度学习的雷达目标识别模型，采用AConvNet架构',
      state: 'ready',
      json: {
        evaluate: {
          test_image: 'images/radar_test.png',
          acc_value: '0.952',
          cpu_occupancy: '45%',
          gpu_occupancy: '78%',
          memory_occupancy: '2.3GB'
        },
        compress: {
          compress_algorithm_id: 'ALG_001',
          'pre-compression_acc': '0.952',
          compressed_acc: '0.945',
          'pre-compression_size': '120MB',
          compressed_size: '45MB',
          compression_ratio: '2.67'
        },
        format: {
          input_size: '224x224',
          raw: 'PyTorch',
          final: 'ONNX'
        }
      }
    },
    {
      key: 'model_002',
      modelId: 'MODEL_002',
      name: '变化检测Siamese U-Net',
      location: '/models/change_detection/siamese_unet',
      type: '变化检测',
      attribute: 'Siamese U-Net架构的遥感图像变化检测模型',
      state: 'ready',
      json: {
        evaluate: {
          test_image: 'images/change_test.png',
          acc_value: '0.923',
          cpu_occupancy: '52%',
          gpu_occupancy: '65%',
          memory_occupancy: '3.1GB'
        },
        compress: {
          compress_algorithm_id: 'ALG_002',
          'pre-compression_acc': '0.923',
          compressed_acc: '0.918',
          'pre-compression_size': '85MB',
          compressed_size: '32MB',
          compression_ratio: '2.66'
        },
        format: {
          input_size: '512x512',
          raw: 'TensorFlow',
          final: 'TensorRT'
        }
      }
    },
    {
      key: 'model_003',
      modelId: 'MODEL_003',
      name: '云检测Cloud-Net',
      location: '/models/cloud_detection/cloudnet',
      type: '云检测',
      attribute: '基于深度神经网络的卫星图像云检测模型',
      state: 'ready',
      json: {
        evaluate: {
          test_image: 'images/cloud_test.png',
          acc_value: '0.934',
          cpu_occupancy: '38%',
          gpu_occupancy: '56%',
          memory_occupancy: '1.8GB'
        },
        compress: {
          compress_algorithm_id: 'ALG_003',
          'pre-compression_acc': '0.934',
          compressed_acc: '0.928',
          'pre-compression_size': '95MB',
          compressed_size: '38MB',
          compression_ratio: '2.5'
        },
        format: {
          input_size: '256x256',
          raw: 'PyTorch',
          final: 'ONNX'
        }
      }
    },
    {
      key: 'model_004',
      modelId: 'MODEL_004',
      name: '导航识别Social-LSTM',
      location: '/models/navigation/social_lstm',
      type: '轨迹预测',
      attribute: 'Social-LSTM模型用于行人轨迹预测和导航决策',
      state: 'ready',
      json: {
        evaluate: {
          test_image: 'images/nav_test.png',
          acc_value: '0.876',
          cpu_occupancy: '42%',
          gpu_occupancy: '67%',
          memory_occupancy: '2.5GB'
        },
        compress: {
          compress_algorithm_id: 'ALG_004',
          'pre-compression_acc': '0.876',
          compressed_acc: '0.871',
          'pre-compression_size': '78MB',
          compressed_size: '29MB',
          compression_ratio: '2.69'
        },
        format: {
          input_size: '64x64',
          raw: 'TensorFlow',
          final: 'TFLite'
        }
      }
    },
    {
      key: 'model_005',
      modelId: 'MODEL_005',
      name: '目标检测Faster R-CNN',
      location: '/models/detection/faster_rcnn',
      type: '目标检测',
      attribute: 'Faster R-CNN目标检测模型，适用于多类别目标识别',
      state: 'ready',
      json: {
        evaluate: {
          test_image: 'images/detection_test.png',
          acc_value: '0.915',
          cpu_occupancy: '68%',
          gpu_occupancy: '89%',
          memory_occupancy: '4.2GB'
        },
        compress: {
          compress_algorithm_id: 'ALG_005',
          'pre-compression_acc': '0.915',
          compressed_acc: '0.908',
          'pre-compression_size': '158MB',
          compressed_size: '62MB',
          compression_ratio: '2.55'
        },
        format: {
          input_size: '800x600',
          raw: 'PyTorch',
          final: 'ONNX'
        }
      }
    },
    {
      key: 'model_006',
      modelId: 'MODEL_006',
      name: '图像分割UNet',
      location: '/models/segmentation/unet',
      type: '图像分割',
      attribute: 'U-Net架构的卫星图像分割模型',
      state: 'ready',
      json: {
        evaluate: {
          test_image: 'images/seg_test.png',
          acc_value: '0.942',
          cpu_occupancy: '55%',
          gpu_occupancy: '72%',
          memory_occupancy: '3.5GB'
        },
        compress: {
          compress_algorithm_id: 'ALG_006',
          'pre-compression_acc': '0.942',
          compressed_acc: '0.938',
          'pre-compression_size': '102MB',
          compressed_size: '41MB',
          compression_ratio: '2.49'
        },
        format: {
          input_size: '512x512',
          raw: 'TensorFlow',
          final: 'TensorRT'
        }
      }
    },
    {
      key: 'model_007',
      modelId: 'MODEL_007',
      name: '图像超分辨率重建SRCNN',
      location: '/models/super_resolution/srcnn',
      type: '超分辨率',
      attribute: 'SRCNN超分辨率重建模型，提升图像清晰度',
      state: 'ready',
      json: {
        evaluate: {
          test_image: 'images/sr_test.png',
          acc_value: '0.889',
          cpu_occupancy: '35%',
          gpu_occupancy: '58%',
          memory_occupancy: '1.9GB'
        },
        compress: {
          compress_algorithm_id: 'ALG_007',
          'pre-compression_acc': '0.889',
          compressed_acc: '0.885',
          'pre-compression_size': '45MB',
          compressed_size: '18MB',
          compression_ratio: '2.5'
        },
        format: {
          input_size: '128x128',
          raw: 'PyTorch',
          final: 'ONNX'
        }
      }
    },
    {
      key: 'model_008',
      modelId: 'MODEL_008',
      name: '图像分类ResNet50',
      location: '/models/classification/resnet50',
      type: '图像分类',
      attribute: 'ResNet50深度残差网络用于图像分类任务',
      state: 'ready',
      json: {
        evaluate: {
          test_image: 'images/class_test.png',
          acc_value: '0.967',
          cpu_occupancy: '48%',
          gpu_occupancy: '71%',
          memory_occupancy: '2.8GB'
        },
        compress: {
          compress_algorithm_id: 'ALG_008',
          'pre-compression_acc': '0.967',
          compressed_acc: '0.962',
          'pre-compression_size': '98MB',
          compressed_size: '39MB',
          compression_ratio: '2.51'
        },
        format: {
          input_size: '224x224',
          raw: 'TensorFlow',
          final: 'TFLite'
        }
      }
    },
    {
      key: 'model_009',
      modelId: 'MODEL_00*',
      name: '目标检测YOLO',
      location: '/models/detection/YOLO',
      type: '目标检测',
      attribute: 'YOLO模型用于目标检测任务',
      state: 'ready',
      json: {
        evaluate: {
          test_image: 'images/class_test.png',
          acc_value: '0.958',
          cpu_occupancy: '57%',
          gpu_occupancy: '72%',
          memory_occupancy: '2.5GB'
        },
        compress: {
          compress_algorithm_id: 'ALG_009',
          'pre-compression_acc': '0.932',
          compressed_acc: '0.956',
          'pre-compression_size': '96MB',
          compressed_size: '38MB',
          compression_ratio: '2.52'
        },
        format: {
          input_size: '224x224',
          raw: 'PyTorch',
          final: 'PTH'
        }
      }
    }
  ];

  const [data, setData] = useState(staticData);
  const [editingKey, setEditingKey] = useState('');
  const [visible, setVisible] = useState(false);
  const [imageSrc, setImageSrc] = useState('');
  const navigate = useNavigate();
  const [form] = Form.useForm();
  // 上传模型参数界面是否可见
  const [uploadModelParamIsVisible, setuploadModelParamIsVisible] = useState(false)

  const isEditing = (record) => record.key === editingKey;

  const edit = (record) => {
    form.setFieldsValue({
      name: '',
      location: '',
      type: '',
      attribute: '',
      state: '',
      ...record,
    });
    setEditingKey(record.key);
  };

  const cancel = () => {
    setEditingKey('');
  };

  const save = async (key) => {
    try {
      const row = await form.validateFields();
      const newData = [...data];
      const index = newData.findIndex((item) => key === item.key);

      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row });
        setData(newData);
        setEditingKey('');

        // 这里可以添加保存到本地存储或其他持久化逻辑
        console.log('模型信息已更新:', { ...item, ...row });
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };

  // const handleUploadClick = (record) => {
  //   navigate('/manage', { state: { selectedKey: 'uploadPage', ...record } });
  // };

  const handleImageClick = (src) => {
    setImageSrc(src);
    setVisible(true);
  };

  const stateMap = {
    uploading: '上传中',
    validate: '检验中',
    compress: '压缩中',
    evaluate: '验证中',
    ready: '就绪',
  };

  const columns = [
    {
      title: '模型ID',
      dataIndex: 'modelId',
      editable: false,
    },
    {
      title: '名称',
      dataIndex: 'name',
      editable: true,
    },
    {
      title: '位置',
      dataIndex: 'location',
      editable: true,
    },
    {
      title: '类型',
      dataIndex: 'type',
      editable: true,
    },
    {
      title: '模型描述',
      dataIndex: 'attribute',
      editable: true,
    },
    {
      title: '状态',
      dataIndex: 'state',
      editable: true,
      render: (text) => (
        <Badge
          status={text === 'ready' ? 'success' : 'processing'}
          text={stateMap[text]}
        />
      ),
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Button
              type="primary"
              onClick={() => save(record.key)}
              style={{ marginRight: 8 }}
            >
              确认保存
            </Button>
            <Button onClick={cancel}>取消</Button>
          </span>
        ) : (
          <span>
            <Button onClick={() => edit(record)} style={{ marginRight: 8 }} ghost>
              编辑
            </Button>
            <Button onClick={updateModel} ghost>卫星模型更新</Button>
            {/*<Button onClick={() => handleUploadClick(record)} ghost>*/}
            {/*  重传*/}
            {/*</Button>*/}
            {/*<Button ghost>*/}
            {/*  上星*/}
            {/*</Button>*/}
          </span>
        );
      },
    },
  ];

  const expandedRowRender = (record) => {
    const columns = [
      { title: '数据图表', dataIndex: ['evaluate', 'test_image'], key: 'test_image', render: (text) => text ? <Button onClick={() => handleImageClick(`http://39.106.250.42:5172/${text}`)}>View Image</Button> : 'No Image' },
      { title: '准确度', dataIndex: ['evaluate', 'acc_value'], key: 'acc_value' },
      { title: 'CPU占用', dataIndex: ['evaluate', 'cpu_occupancy'], key: 'cpu_occupancy' },
      { title: 'GPU占用', dataIndex: ['evaluate', 'gpu_occupancy'], key: 'gpu_occupancy' },
      { title: '内存占用', dataIndex: ['evaluate', 'memory_occupancy'], key: 'memory_occupancy' },
      { title: '压缩算法ID', dataIndex: ['compress', 'compress_algorithm_id'], key: 'compress_algorithm_id' },
      { title: '压缩前准确度', dataIndex: ['compress', 'pre-compression_acc'], key: 'pre_compression_acc' },
      { title: '压缩后准确度', dataIndex: ['compress', 'compressed_acc'], key: 'compressed_acc' },
      { title: '压缩前体积', dataIndex: ['compress', 'pre-compression_size'], key: 'pre_compression_size' },
      { title: '压缩后体积', dataIndex: ['compress', 'compressed_size'], key: 'compressed_size' },
      { title: '压缩率', dataIndex: ['compress', 'compression_ratio'], key: 'compression_ratio' },
      { title: '输入大小', dataIndex: ['format', 'input_size'], key: 'input_size' },
      { title: '原始格式', dataIndex: ['format', 'raw'], key: 'raw' },
      { title: '最终格式', dataIndex: ['format', 'final'], key: 'final' }
    ];

    return <Table columns={columns} dataSource={[record.json]} pagination={false} rowKey="test_image" />;
  };

  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  // 自定义分页器：在"上一页即 < "左侧添加按钮
  const itemRender = (current, type, originalElement) => {
    if (type === 'prev') {
      return (
        <Space>
          <Button style={{ marginRight: 8, color: '#fff' }} ghost onClick={addModelItem}>
            添加卫星模型
          </Button>
          {originalElement}
        </Space>
      );
    }
    return originalElement;
  }

  // 点击添加模型
  const addModelItem = () => {
    const newKey = `model_${String(data.length + 1).padStart(3, '0')}`
    const newRow = {
      key: newKey,
      modelId: `MODEL_${String(data.length + 1).padStart(3, '0')}`,
      name: '',
      location: '',
      type: '',
      attribute: '',
      state: '',
    }
    setData([...data, newRow])
    setEditingKey(newKey);
  };

  // 模型更新
  const updateModel = () => {
    setuploadModelParamIsVisible(true)
    console.log(111)
  }

  return (
    <div style={{ padding: '10px', minHeight: '100%', backgroundColor: 'transparent' }} className='model-manage-table'>
      <Form form={form} component={false}>
        <Table
          components={{
            body: {
              cell: EditableCell,
            },
          }}
          rowHoverable='False'
          dataSource={data}
          columns={mergedColumns}
          rowClassName="editable-row"
          pagination={{
            pageSize: 15,
            itemRender: itemRender, // 自定义左侧按钮
          }}
          rowKey="key"
          expandable={{ expandedRowRender }}
          scroll={{ x: 'max-content' }}
          style={{ maxWidth: '100%' }}
        />
      </Form>
      <Modal visible={visible} footer={null} onCancel={() => setVisible(false)} style={{ backgroundColor: 'rgba(16, 58, 91, 0.85)', borderRadius: '0', border: '1px solid rgba(126, 156, 179, 0.8)' }}>
        <img alt="Test" style={{ width: '100%' }} src={imageSrc} />
      </Modal>

      <UploadModalParam
        visible={uploadModelParamIsVisible}
        onClose={() => setuploadModelParamIsVisible(false)}
        // onUploadComplete={handleUploadComplete}
        // accept=".jpg,.png,.pdf"  // 可指定文件类型
        title="卫星模型更新"
      />
    </div>
  );
};

export default ModelManage;